using System.Web.UI;
using log4net;
using Quiki.ExpressionParsers;

namespace Quiki.ElementFormatters
{
    public class ListItemElementFormatter : ElementFormatterBase
    {
        public override bool FormatBegin (WikiTextElement element, HtmlFormatterContext context)
        {
            if (false == (element.ElementType == WikiTextElementType.ListDefinition
                || element.ElementType == WikiTextElementType.ListOrdered
                || element.ElementType == WikiTextElementType.ListUnordered))
                return false;

            if (context.CurrentParagraphType != element.ElementType)
            {
                if (log.IsDebugEnabled)
                    log.DebugFormat(
                        "FormatBegin: current={0}, new={1}. Closing all paragraphs",
                        context.CurrentParagraphType,
                        element.ElementType);
                context.CloseAllParagraphs();

                switch (element.ElementType)
                {
                    case WikiTextElementType.ListDefinition:
                        context.PushTag(HtmlTextWriterTag.Dl);
                        break;
                    case WikiTextElementType.ListOrdered:
                        context.PushTag(HtmlTextWriterTag.Ol);
                        break;
                    case WikiTextElementType.ListUnordered:
                        context.PushTag(HtmlTextWriterTag.Ul);
                        break;
                }
            }

            context.CurrentParagraphType = element.ElementType;

            switch (element.ElementType)
            {
                case WikiTextElementType.ListDefinition:
                    context.PushTag(HtmlTextWriterTag.Dd);
                    break;
                case WikiTextElementType.ListOrdered:
                case WikiTextElementType.ListUnordered:
                    context.PushTag(HtmlTextWriterTag.Li);
                    break;
            }

            return true;
        }

        public override void FormatEnd (WikiTextElement element, HtmlFormatterContext context)
        {
            if (false == (element.ElementType == WikiTextElementType.ListDefinition
                || element.ElementType == WikiTextElementType.ListOrdered
                || element.ElementType == WikiTextElementType.ListUnordered))
                return;

            context.PopTag();
            context.Writer.WriteLine ();
        }

        private static readonly ILog log = LogManager.GetLogger(typeof(ListItemElementFormatter));
    }
}